package com.kwshare.gateway.handler;

import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 网关统一异常处理
 *
 * @author yangjing
 */
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler, Ordered {

    /**
     * 异常处理
     *
     * @param exchange,ex
     * @return 结果
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        // 响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 响应消息
        String msg = null;
        if(response.isCommitted()){
            return Mono.error(ex);
        }
        // 服务未找到
        if (ex instanceof NotFoundException){
            msg = "服务未找到";
        }
        // 设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 设置请求头
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        // 构建DataBuffer对象
        DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 处理器执行顺序
     *
     * @param
     * @return 结果
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
